#include <ez80F91.h>
#include <stdio.h>
#include "shell.h"
#include "ZSysgen.h"
#include "ZTypes.h"
#include "ZThread.h"
#include "HVACControl.h"
#include "sleep.h"
#include "temperature.h"
#include "eeprom.h"
#include "WLAN.h"
#ifdef RUNNING_STATE_TRANS_TESTS
	#include "testing.h"
#endif
#include "History.h"
#include "ZTimer.h"

// external variables
extern RZK_DEVICE_CB_t *CONSOLE;

// function prototypes
extern void InitUART(void);

TICK_t ticksPerSecond;

// entry point for application
INT16 ZTPAppEntry(void)
{
	RZK_DEVICE_CB_t *TTYDevID;
	struct devCap *devSerial;

	devSerial = (struct devCap *)malloc(sizeof(struct devCap));
	devSerial->devHdl = (VOID *)CONSOLE; 
	devSerial->devType = 0;
	TTYDevID = RZKDevOpen("TTYM", (RZK_DEV_MODE_t*)devSerial);
	if(TTYDevID == NULL)
	{
	   	printf("Can't open tty for SERIAL0\n");
		return SYSERR;
	}

	printf("\n*** Booted ***\n");

	ticksPerSecond = RZKGetTimerResolution();

	sleepInit();

	if (temperatureInit())
	{
	   	printf("Can't initialize digital thermometer\n");
#ifndef _DEBUG
		shell_init(TTYDevID);
		return SYSERR;
#endif
	}
	else
	   	printf("Digital thermometer initialized\n");

	if (eepromInit())
	{
	   	printf("Can't initialize EEPROM settings\n");
#ifndef _DEBUG
		shell_init(TTYDevID);
		return SYSERR;
#endif
	}
	else
	   	printf("EEPROM settings initialized\n");

	if(initTempControl() != SUCCESS)
	{
#ifndef _DEBUG
		shell_init(TTYDevID);
		return SYSERR;
#endif
	}

	if (WLANInit())
	{
	   	printf("Can't initialize WLAN\n");
#ifndef _DEBUG
		shell_init(TTYDevID);
		return SYSERR;
#endif
	}
	else
	   	printf("WLAN initialized\n");


	if(initHistory() != SUCCESS)
	{
		printf("Could not start history logging\n");
	}

	// Now start the timers
	if(startHVACTimer() != SUCCESS)
	{
		shell_init(TTYDevID);
		return SYSERR;
	}
	if(startWLANTimer() != SUCCESS)
	{
		shell_init(TTYDevID);
		return SYSERR;
	}

	shell_init(TTYDevID);

#ifdef RUNNING_STATE_TRANS_TESTS
	sleep2Init();
	sleep2(1000);
	if(initTesting() != SUCCESS)
	{
		return SYSERR;
	}
#endif

	return OK;
}
